package com.java1234.view;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;

import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.table.DefaultTableModel;

import com.java1234.dao.IReturnBookDao;
import com.java1234.dao.impl.ReturnBookImpl;
import com.java1234.model.Borrow;
import com.java1234.model.ReturnBook;
import com.java1234.util.DbUtil;
import com.java1234.util.StringUtil;

public class BookReturnManageInterFrm extends JInternalFrame {
	private JTable bookReturnTable;

	private DbUtil dbUtil = new DbUtil();
	private IReturnBookDao returnBookDao = new ReturnBookImpl();
	private JTextField s_borrowerAccountTxt;
	private JTextField borrowerAccountTxt;
	private JTextField bookIdTxt;
	private JTextField statusTxt;
	private JTextField borrowTimeTxt;
	private JTextField returnTimeTxt;
	private JTextField fineTxt;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					BookReturnManageInterFrm frame = new BookReturnManageInterFrm();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public BookReturnManageInterFrm() {
		setIconifiable(true);
		setClosable(true);
		setTitle("图书归还处理");
		setBounds(100, 100, 953, 717);

		JScrollPane scrollPane = new JScrollPane();

		JButton btnNewButton = new JButton("归还");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				returnActionPerformed(e);
			}
		});

		JLabel lblNewLabel = new JLabel("借阅者账号：");

		s_borrowerAccountTxt = new JTextField();
		s_borrowerAccountTxt.setColumns(10);

		JButton btnNewButton_1 = new JButton("查询");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				borrowerAccountSearchActionPerformed(e);
			}
		});

		JButton btnNewButton_2 = new JButton("续借");
		btnNewButton_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					renewActionPerformed(e);
				} catch (ParseException e1) {
					
					e1.printStackTrace();
				}
			}
		});

		JLabel lblNewLabel_1 = new JLabel("借阅者账号：");

		borrowerAccountTxt = new JTextField();
		borrowerAccountTxt.setEditable(false);
		borrowerAccountTxt.setColumns(10);

		JLabel lblNewLabel_2 = new JLabel("图书编号：");

		bookIdTxt = new JTextField();
		bookIdTxt.setEditable(false);
		bookIdTxt.setColumns(10);

		JLabel lblNewLabel_4 = new JLabel("状态：");

		statusTxt = new JTextField();
		statusTxt.setEditable(false);
		statusTxt.setColumns(10);

		JLabel lblNewLabel_3 = new JLabel("借阅时间：");

		JLabel lblNewLabel_5 = new JLabel("还书时间：");

		borrowTimeTxt = new JTextField();
		borrowTimeTxt.setEditable(false);
		borrowTimeTxt.setColumns(10);

		returnTimeTxt = new JTextField();
		returnTimeTxt.setEditable(false);
		returnTimeTxt.setColumns(10);
		
		JLabel lblNewLabel_6 = new JLabel("超期罚款：");
		
		fineTxt = new JTextField();
		fineTxt.setEditable(false);
		fineTxt.setColumns(10);
		
		JButton btnNewButton_3 = new JButton("罚款清零");
		btnNewButton_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				fineZeroActionPerformed(e);
			}
		});
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap(49, Short.MAX_VALUE)
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(63)
							.addComponent(lblNewLabel)
							.addGap(59)
							.addComponent(s_borrowerAccountTxt, GroupLayout.PREFERRED_SIZE, 241, GroupLayout.PREFERRED_SIZE)
							.addGap(35)
							.addComponent(btnNewButton_1))
						.addGroup(groupLayout.createSequentialGroup()
							.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
								.addComponent(lblNewLabel_3)
								.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
									.addComponent(btnNewButton_2)
									.addComponent(btnNewButton_3))
								.addComponent(lblNewLabel_1))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
								.addGroup(groupLayout.createSequentialGroup()
									.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
										.addComponent(borrowTimeTxt)
										.addComponent(borrowerAccountTxt, GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE))
									.addGap(65)
									.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
										.addComponent(lblNewLabel_2)
										.addComponent(lblNewLabel_5)
										.addComponent(lblNewLabel_6)))
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(btnNewButton)
									.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
									.addComponent(lblNewLabel_4)))
							.addGap(40)
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
								.addComponent(fineTxt)
								.addComponent(returnTimeTxt, GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE)
								.addGroup(groupLayout.createSequentialGroup()
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(bookIdTxt))
								.addComponent(statusTxt)))
						.addGroup(groupLayout.createSequentialGroup()
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 842, GroupLayout.PREFERRED_SIZE)))
					.addGap(46))
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGap(49)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(s_borrowerAccountTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblNewLabel)
						.addComponent(btnNewButton_1))
					.addGap(59)
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 287, GroupLayout.PREFERRED_SIZE)
					.addGap(33)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(borrowerAccountTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblNewLabel_2)
						.addComponent(bookIdTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblNewLabel_1))
					.addGap(46)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNewLabel_3)
						.addComponent(lblNewLabel_5)
						.addComponent(borrowTimeTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(returnTimeTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(39)
							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(statusTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblNewLabel_4))
							.addPreferredGap(ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblNewLabel_6)
								.addComponent(fineTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addGap(23))
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(18)
							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(btnNewButton_2)
								.addComponent(btnNewButton))
							.addGap(30)
							.addComponent(btnNewButton_3)
							.addGap(30))))
		);

		bookReturnTable = new JTable();
		bookReturnTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				bookReturnTableMousePressed(e);
			}
		});
		bookReturnTable.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u501F\u9605\u8005\u8D26\u53F7", "\u56FE\u4E66\u7F16\u53F7", "\u501F\u9605\u65F6\u95F4", "\u8FD8\u4E66\u65F6\u95F4", "\u72B6\u6001", "\u8D85\u671F\u7F5A\u6B3E"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false, false, false, false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		scrollPane.setViewportView(bookReturnTable);
		getContentPane().setLayout(groupLayout);
		this.fillTable(new ReturnBook());
	}

//	@Test
//	public void testFindAll() throws Exception {
//		System.out.println("查询所有图书");
//		List<ReturnBook> list = returnBookDao.findAll();
//		for (ReturnBook returnBook : list) {
//			System.out.println(returnBook);
//		}
//	}
	/**
	 * 初始化表格
	 * 
	 * @param bookType
	 */
	private void fillTable(ReturnBook returnBook) {
		DefaultTableModel dtm = (DefaultTableModel) bookReturnTable.getModel();
		dtm.setRowCount(0);// 设置成0行
		Connection con = null;
		try {
			con = dbUtil.getCon();
//			List<ReturnBook> rs = returnBookDao.findAll();
			ResultSet rs = returnBookDao.list(con, returnBook);
			while (rs.next()) {
				Vector v = new Vector();
				v.add(rs.getString("borrowerAccount"));
				v.add(rs.getString("bookId"));
				v.add(rs.getDate("borrowTime"));
				v.add(rs.getDate("returnTime"));
				v.add(rs.getString("status"));
				v.add(rs.getInt("fine"));
				dtm.addRow(v);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 借阅者账号搜索事件处理
	 * 
	 * @param e
	 */
	private void borrowerAccountSearchActionPerformed(ActionEvent evt) {
		String s_borrowerAccount = this.s_borrowerAccountTxt.getText();
		ReturnBook returnBook=new ReturnBook();
		returnBook.setBorrowerAccount(s_borrowerAccount);
		this.fillTable(returnBook);
	}
	/**
	 * 表格行点击事件处理
	 * 
	 * @param e
	 */
	private void bookReturnTableMousePressed(MouseEvent evt) {
		int row = bookReturnTable.getSelectedRow();
		borrowerAccountTxt.setText((String) bookReturnTable.getValueAt(row, 0));
		bookIdTxt.setText((String) bookReturnTable.getValueAt(row, 1));

		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date) bookReturnTable.getValueAt(row, 2);
		String time = ft.format(date);
		borrowTimeTxt.setText(time);
		date = (Date) bookReturnTable.getValueAt(row, 3);
		String time2 = ft.format(date);
		returnTimeTxt.setText(time2);
		statusTxt.setText((String) bookReturnTable.getValueAt(row, 4));// getValueAt(int row, int column) 返回 row 和column 位置的单元格值。
		int number=((int) bookReturnTable.getValueAt(row, 5));
		String fine=String.valueOf(number);//int转String
		fineTxt.setText(fine);
	}

	/**
	 * 图书续借事件处理
	 * 
	 * @param evt
	 * @throws ParseException
	 */
	private void renewActionPerformed(ActionEvent evt) throws ParseException {
		String bookId = this.bookIdTxt.getText();

		if (StringUtil.isEmpty(bookId)) {
			JOptionPane.showMessageDialog(null, "请选择要借的书");
			return;
		}
		String borrowerAccount = this.borrowerAccountTxt.getText();
		String status = this.statusTxt.getText();

		if (StringUtil.isEmpty(borrowerAccount)) {
			JOptionPane.showMessageDialog(null, "未输入借阅者！");
			return;
		}
		if (StringUtil.isEmpty(status)) {
			JOptionPane.showMessageDialog(null, "未输入图书状态！");
			return;
		}

		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");

		Date borrowTime = (Date) ft.parse(this.borrowTimeTxt.getText());


		Date returnTime = (Date) ft.parse(this.returnTimeTxt.getText());

		ReturnBook returnBook = new ReturnBook(borrowerAccount, bookId, borrowTime, returnTime, status);

		Connection con = null;
		try {
			con = dbUtil.getCon();
			int addNum = returnBookDao.update(con, returnBook);
			if (addNum == 1 && returnBook.getStatus().equals("已借出")) {
				JOptionPane.showMessageDialog(null, "续借成功！");// 借出状态修改不了（没变化）解决方案：在impl里改set
				resetValueActionPerformed();
				this.fillTable(new ReturnBook());
			}else if (addNum == 1 && returnBook.getStatus().equals("续借1次")) {
				JOptionPane.showMessageDialog(null, "续借成功！");
				resetValueActionPerformed();
				this.fillTable(new ReturnBook());
			}
			else {
				JOptionPane.showMessageDialog(null, "不能再次续借！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "续借失败！");
		} finally {
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 图书归还事件处理
	 * 
	 * @param evt
	 */
	private void returnActionPerformed(ActionEvent evt) {
		String bookId = this.bookIdTxt.getText();

		if (StringUtil.isEmpty(bookId)) {
			JOptionPane.showMessageDialog(null, "请选择要还的书");
			return;
		}
		String borrowerAccount = this.borrowerAccountTxt.getText();

		String status = this.statusTxt.getText();
		

		if (StringUtil.isEmpty(borrowerAccount)) {
			JOptionPane.showMessageDialog(null, "未输入借阅者！");
			return;
		}
		if (StringUtil.isEmpty(bookId)) {
			JOptionPane.showMessageDialog(null, "未输入图书状态！");
			return;
		}
		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");

		Date returnTime = null;
		try {
			returnTime = (Date) ft.parse(this.returnTimeTxt.getText());
		} catch (ParseException e1) {
			
			e1.printStackTrace();
		}
		
		
		
		String fine1 = this.fineTxt.getText();
		int fine=Integer.parseInt(fine1);
		
		
		ReturnBook returnBook = new ReturnBook(bookId, returnTime, fine);

		Connection con = null;
		try {
			con = dbUtil.getCon();
			int flag = returnBookDao.fine(con, returnBook);
			if (flag != 0) {
				JOptionPane.showMessageDialog(null, "请先支付罚款");
				return;
			}
			int addNum = returnBookDao.delete(con, bookId);
			if (addNum == 1) {
				JOptionPane.showMessageDialog(null, "还书成功！");// 借出状态修改不了（没变化）解决方案：在impl里改set
				resetValueActionPerformed();
				this.fillTable(new ReturnBook());
				returnBookDao.returnBook(con, returnBook);

			} else {
				JOptionPane.showMessageDialog(null, "还书失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "还书失败！");
		} finally {
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 罚款清零事件处理
	 * 
	 * @param evt
	 */
	private void fineZeroActionPerformed(ActionEvent evt) {
		String bookId = this.bookIdTxt.getText();
		String fine1 = this.fineTxt.getText();
		
		int fine=Integer.parseInt(fine1);
		ReturnBook returnBook = new ReturnBook(bookId,fine);

		Connection con = null;
		try {
			con = dbUtil.getCon();
			int addNum = returnBookDao.fineZero(con, returnBook);
			if (addNum == 1) {
				JOptionPane.showMessageDialog(null, "罚款清零成功！");// 借出状态修改不了（没变化）解决方案：在impl里改set
				resetValueActionPerformed();
				this.fillTable(new ReturnBook());
			} else {
				JOptionPane.showMessageDialog(null, "罚款清零失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "罚款清零失败！");
		} finally {
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
	}

	/**
	 * 重置事件处理
	 * 
	 * @param e
	 */
	private void resetValueActionPerformed() {
		this.borrowerAccountTxt.setText("");
		this.bookIdTxt.setText("");
		this.borrowTimeTxt.setText("");
		this.returnTimeTxt.setText("");
		this.statusTxt.setText("");
		this.fineTxt.setText("");
	}

	public JTable getBookReturnTable() {
		return bookReturnTable;
	}

	public void setBookReturnTable(JTable bookReturnTable) {
		this.bookReturnTable = bookReturnTable;
	}
}
